package com.stackfarm.fvservice.service.influxdb.Impl;

import com.stackfarm.fvcommon.result.SensorData;
import com.stackfarm.fvservice.config.InfluxDBConfig;
import com.stackfarm.fvservice.service.influxdb.SensorDataService;
import org.influxdb.dto.QueryResult;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@Service
public class SensorDataServiceImpl implements SensorDataService {
    @Resource
    InfluxDBConfig influxDBConfig;

    @Override
    public SensorData requestData(String type, Long startTime, Long endTime) {
        String str = "select * from db2 where type='" + type + "'" + " and time>=" + startTime + "000000 and time<=" + endTime + "000000;";
        //String str = "select * from db1 where type='"+"temp"+"'"+" and time>="+webRequest.getStartTime()+"000000 and time<="+webRequest.getEndTime()+"000000;";
        QueryResult rs = influxDBConfig.query(str);
        List<Map<String, Object>> rsList = influxDBConfig.queryResultProcess(rs);
        SensorData sensorData = new SensorData();
        List<List<Object>> d = new ArrayList<>();
        for (Map<String, Object> x : rsList) {
            Long t;
            org.joda.time.DateTime dateTime = new DateTime(x.get("time"));
            t = dateTime.toCalendar(Locale.getDefault()).getTimeInMillis();
            Double v = (Double) x.get("value");
            List<Object> obj = new ArrayList<>();
            obj.add(0, t);
            obj.add(1, v);
            d.add(obj);
        }
        sensorData.setType(type);
        sensorData.setData(d);
        return sensorData;
    }

    @Override
    public List<SensorData> requestDatas(Long startTime, Long endTime, List<String> type) {
        List<SensorData> res = new ArrayList<>();
        for (String e:type) {
            res.add(requestData(e,startTime,endTime));
        }
        return res;
    }
}
